// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
	env: "wxd13ec5e936e7d88d"
}) // 使用当前云环境
const ExcelJS = require('exceljs')

const db = uniCloud.database();
// 云函数入口函数
exports.main = async (event, context) => {

	// 前端传入数据
	let data = event.data
	
	console.log(event.data);

	data.sort(function(a, b) {
		return a.date - b.date;
	});
	
	
	let atPresentYear = new Date(data[0].createTime).getFullYear()  //获取当前年
	let atPresentMonth = new Date(data[0].createTime).getMonth() + 1 < 10 ? '0' + (new Date(data[0].createTime).getMonth() + 1) : new Date(data[0].createTime).getMonth() + 1  //获取当前月
	let atYearMonth = atPresentYear + '-' + atPresentMonth  //当前年月
	
	let dataCVS = `schoolExcel-${Math.floor(Math.random()*100000000)}.xlsx`
	
	// 生成表格的函数
	const exportExcel = async () => {
		// 创建工作簿
		_workbook = new ExcelJS.Workbook();
		// 添加工作表
		_sheet1 = _workbook.addWorksheet(atPresentMonth +  "月份工作量");
		
		
		function generateFormattedExcelColumns() {  
		    let columns = [];  
		  
		    for (let i = 0; i < 26; i++) {  
		        columns.push(String.fromCharCode(65 + i));  
		    }  
		  
		    for (let i = 0; i < 26; i++) {  
		        for (let j = 0; j < 26; j++) {  
		            if (j === 0) {  
		                continue;  
		            }  
		            columns.push(String.fromCharCode(65 + i) + String.fromCharCode(65 + j));  
		        }  
		    }  
		  
		    return columns;  
		}  
		  
			
		let excelList = generateFormattedExcelColumns();  
		console.log(excelList , '-----------------------------------------');
		
		// 头部
		let header = [
			{
				header: "工作量统计",
				key: "index",
				width: 15
			},
			{
				key: "name",
				width: 15
			}
		]
		
		// 内容
		let addRowList = [
			{
				name: "",
				index:`${atPresentYear}.${atPresentMonth}`
			},
			
			{
				name: "姓名",
				index:'序号'
			},
			
			{
				name: "何俊东",
				index:1
			},
			
			{
				name: "",
				index:'合计'
			},
			{
				name: "",
				index:'图标说明：全勤√ 迟到▲ 早退● 旷工☆ 事假◆ 病假◇ 年假△ 调休〓 公出■ 出差□ 婚假§ 丧假◎  加班⊕；'
			}
		]
		
		let statistics = {
			date:0 ,// 工作天数
			hour:0 ,//调休
			takeWorkingDaysOff:0
		}
		
		data.forEach((item, index) => {
			let str = ''
			// 正常 上班时长
			if (item.workingHours != 0) {
				str += item.workingHours == 8 ? '√' : '√' + item.workingHours + 'h'
			}

			// 加班时长
			if (item.overtime != 0) {
				statistics.hour += Number(item.overtime)
				str += '⊕' + item.overtime + 'h'
			}

			// 调休时间
			if (item.leave != 0) {
				statistics.takeWorkingDaysOff += Number(item.leave)
				str += '〓' + item.leave + 'h'
			}

			header.push({
				header: '',
				key: 'condition' + index,
				width: 10
			})
			
			// 计算当月出勤天数
			let day = new Date(item.createTime).getDay()
			console.log(day , 'day------------------------');
			if(day != 0 && day != 6){
				statistics.date += 1
			}
			
			// 计算加班时长

			// 设置当前行数据
			addRowList[0]['condition' + index] = ''
			addRowList[1]['condition' + index] = item.date
			addRowList[2]['condition' + index] = str
		})


		header.push(
			{
				header: "",
				key: "date",
				width: 30
			},
			{
				header: "",
				key: "money",
				width: 30
			},
			{
				header: "",
				key: "hour",
				width: 30
			},
			{
				header: "",
				key: "yuan",
				width: 30
			},
			{
				header: "",
				key: 'takeWorkingDaysOff',
				width: 40
			},
			{
				header: "",
				key: "ramk",
				width: 40
			},
			
		)

		_sheet1.columns = header //设置表头
		
		addRowList[0].date = ''
		addRowList[0].money =''
		addRowList[0].hour = ''
		addRowList[0].yuan = ''
		addRowList[0].takeWorkingDaysOff = ''
		addRowList[0].ramk = ''
		
		
		addRowList[1].date = '本月工作量(天)'
		addRowList[1].money = '标准单价'
		addRowList[1].hour = '贡献值（小时）'
		addRowList[1].yuan = '差旅费（元）'
		addRowList[1].takeWorkingDaysOff = '调休（h）'
		addRowList[1].ramk = '备注'
		
		addRowList[2].date = statistics.date
		addRowList[2].money = '/'
		addRowList[2].hour = statistics.hour
		addRowList[2].yuan = ''
		addRowList[2].ramk = '备注'
		addRowList[2].takeWorkingDaysOff = statistics.takeWorkingDaysOff
		
		addRowList[3].date = statistics.date
		addRowList[3].money = '/'
		addRowList[3].hour = statistics.hour
		addRowList[3].yuan = ''
		addRowList[3].ramk = '/'
		addRowList[3].takeWorkingDaysOff = statistics.takeWorkingDaysOff
		
		addRowList[4].date = ''
		addRowList[4].money =''
		addRowList[4].hour = ''
		addRowList[4].yuan = ''
		addRowList[4].takeWorkingDaysOff = ''
		addRowList[4].ramk = ''

		// 设置列
		addRowList.forEach(item => {
			_sheet1.addRow(item);
		})


		// 设置样式
		const _titleCellOne = _sheet1.getRow(1); // 获取第一行
		const _titleCellTwo = _sheet1.getRow(2); //获取第二行
		const _titleCellThere = _sheet1.getRow(3); //获取第三行
		const _titleCellFour = _sheet1.getRow(4); //获取第四行
		const _titleCellFive = _sheet1.getRow(5); //获取第五行
		const _titleCellSix = _sheet1.getRow(6); //获取第六行

		let setStyleFun = function(
			_titleCell,
			obj = {}
		) {
			
			let configuration = {
				fontWeight: true ,//字体加粗 默认false
				isBackground:false ,// 是否设置底色
				background:'FFFF99',
				mergeNumber:null,  // 需要合并的开始 结束位置序号
				merge:false, //是否需要合并
				currentline:null, //当前行
				rowOrColumn:'row' ,// 行合并或者 列 合并 (默认 行)
				height:30,
				align:"center"
			}
			
			_sheet1.views = [
			  {state: 'frozen', xSplit: 2, ySplit: 0, topLeftCell: 'G10', activeCell: 'A1'}
			];
			
			
			configuration = Object.assign(configuration , obj)  //合并对象
			
			// 设置填充色
			let setFill = function(cell , color = configuration.background ,  pattern = 'solid' , type = 'pattern' ) {
				cell.fill = {
					type: type,
					pattern: pattern,
					fgColor: {
						argb: color,
					},
				};
			}
			
			// 设置边框颜色
			let setBorder = function(cell){
				// 设置边框线的样式
				cell.border = {
					top: {
						style: "thin",
						color: {
							argb: "333333",
						},
					},
					left: {
						style: "thin",
						color: {
							argb: "333333",
						},
					},
					bottom: {
						style: "thin",
						color: {
							argb: "333333",
						},
					},
					right: {
						style: "thin",
						color: {
							argb: "333333",
						},
					},
				};
			}
			
			// 设置文字居中
			let setAlign = function(cell){
				cell.alignment = {
					vertical: "middle",
					horizontal: configuration.align, // 文字居中
				};
			}
			
			// 设置高度
			let setHeight = function(number = configuration.height){
				_titleCell.height = number
			}
			
			if(configuration.height){
			setHeight()
				
			}
			
			
			let setFont = function(cell){
				cell.font = {
					name: "黑体",
					bold: true,
					size: 12,
					color: {
						argb: "000",
					},
				};
			}
			
			
			_titleCell.eachCell((cell, colIdx) => {
				
				let day = new Date(atYearMonth + '-' + cell.value).getDay()
				let white_list = ['本月工作量(天)' , '标准单价' , '贡献值（小时）' , '差旅费（元）' , '调休（h）']
				// 判断是否填充颜色
				if(configuration.isBackground){
					// 判断当前是否为周六日
					if(day == 0 || day == 6 || white_list.includes(cell.value)) {
						// 改变当前单元格样式
						setFill(cell , 'FFFF00')
					}else{
						// 设置单元的样式 - 填充色
						setFill(cell)
					}
				}
				
				setBorder(cell)
				setAlign(cell)
				
				// 判断是否加粗
				if (configuration.fontWeight) {
					setFont(cell)
				}
			});
			
			// 判断是否合并单元格
			if(configuration.merge && configuration.currentline && configuration.mergeNumber){
				// 判断是行还是列合并  (当前默认行 目前只支持行合并)
				if(configuration.rowOrColumn == 'row'){
					// excelList[configuration.currentline - 1]  拿到 excelList 索引对应的位置  开始位置 行   -1 是因为 数组下表从1 开始的 
					// configuration.mergeNumber[0] 开始位置列
					// 行数 + 列数 拿到 如 A1 B2 这样的坐标 位置
					let start = excelList[configuration.mergeNumber[0] - 1] + configuration.currentline
					let end = excelList[configuration.mergeNumber[1] - 1] + configuration.currentline
					console.log(start , end , '---------------------------------');
					_sheet1.mergeCells(`${start}:${end}`);
				}
				
			}
			
		}
		setStyleFun(_titleCellOne , {merge:true , mergeNumber:['1' , header.length - 1] , currentline:1 , rowOrColumn:'row'}) //设置第一行样式 
		setStyleFun(_titleCellTwo , {isBackground:true , background:'FFFF99',merge:true , mergeNumber:['1' , '2'] , currentline:2 , rowOrColumn:'row'})  
		setStyleFun(_titleCellThere , {isBackground:true , background:'CCFFFF'})  //设置第三行样式
		setStyleFun(_titleCellFour , {height:90})
		setStyleFun(_titleCellFive , {merge:true , mergeNumber:['1' , header.length - 7] , currentline:5 , rowOrColumn:'row'})
		setStyleFun(_titleCellSix , {align:'left' , isBackground:true , background:'CCFFCC',merge:true , mergeNumber:['1' , header.length - 1] , currentline:6 , rowOrColumn:'row'})
		

		// 导出表格
		let buffer = await _workbook.xlsx.writeBuffer()
		console.log(buffer, 'buffer');
		let aaa = ''
		let res = await uniCloud.uploadFile({
			cloudPath: dataCVS,
			fileContent: buffer
		})
		// aaa = res
		console.log(res, 'res');

		return res
	};

	let result = await exportExcel()

	// let aaa = ""
	// // // 上传到云存储
	// await uniCloud.uploadFile({
	// 	cloudPath: dataCVS,
	// 	fileContent: buffer
	// }).then(res => {
	// 	aaa = res
	// }).catch(error => {
	// 	aaa = "失败"
	// })
	
	if(result){
		return {
			code:200,
			fileID:result.fileID
		}
	}else {
		return 'error'
	}
}